using System;
using Avalonia.Controls;
using Avalonia.Interactivity;
using System.IO.Ports;
using System.Threading.Tasks;
using IntegratedMeasuring.ViewModels.Entity;
using Avalonia.Markup.Xaml;
using IntegratedMeasuring.Utils;

namespace IntegratedMeasuring.Pages;

public partial class LoginPage : UserControl
{
    public event EventHandler<LoginEventArgs>? LoginRequested;

    public LoginPage()
    {
        InitializeComponent();
        Loaded += LoginPage_Loaded;
    }

    private void InitializeComponent()
    {
        AvaloniaXamlLoader.Load(this);
    }

    private void LoginPage_Loaded(object? sender, RoutedEventArgs e)
    {
        InitializeInstruments();
        InitializePorts();
        GV.LoadGVFromLocalFile();
        ShowGVValues();
    }

    private void InitializeInstruments()
    {
        var instrumentComboBox = this.FindControl<ComboBox>("InstrumentComboBox");
        if (instrumentComboBox != null)
        {
            instrumentComboBox.ItemsSource = Enum.GetValues(typeof(ViewModels.Entity.GC.InstrumentModelType));
        }
    }

    private void ShowGVValues()
    {
        // 设置仪器型号
        var instrumentComboBox = this.FindControl<ComboBox>("InstrumentComboBox");
        if (instrumentComboBox != null)
        {
            instrumentComboBox.SelectedItem = GV.InstrumentModel;
        }
        
        // 设置串口号
        var portComboBox = this.FindControl<ComboBox>("PortComboBox");
        if (portComboBox != null && !string.IsNullOrEmpty(GV.SerialPortNum))
        {
            var portIndex = Array.IndexOf(SerialPort.GetPortNames(), GV.SerialPortNum);
            if (portIndex >= 0)
            {
                portComboBox.SelectedIndex = portIndex;
            }
        }
        
        // 设置波特率
        var baudRateComboBox = this.FindControl<ComboBox>("BaudRateComboBox");
        if (baudRateComboBox != null)
        {
            var baudRateStr = GV.BaudRate.ToString();
            var baudRateIndex = Array.IndexOf(new[] { "9600", "19200", "38400", "57600", "115200" }, baudRateStr);
            if (baudRateIndex >= 0)
            {
                baudRateComboBox.SelectedIndex = baudRateIndex;
            }
        }
        
        // 设置服务器地址
        var serverAddressTextBox = this.FindControl<TextBox>("ServerAddressTextBox");
        if (serverAddressTextBox != null)
        {
            serverAddressTextBox.Text = GV.ServerAddress;
        }
        
        // 设置令牌
        var tokenTextBox = this.FindControl<TextBox>("TokenTextBox");
        if (tokenTextBox != null)
        {
            tokenTextBox.Text = GV.Token;
        }
    }

    private void InitializePorts()
    {
        var portComboBox = this.FindControl<ComboBox>("PortComboBox");
        if (portComboBox != null)
        {
            var ports = SerialPort.GetPortNames();
            portComboBox.ItemsSource = ports;
            if (ports.Length > 0)
                portComboBox.SelectedIndex = 0;
        }
    }

    private void LoginButton_Click(object? sender, RoutedEventArgs e)
    {
        var serverAddressTextBox = this.FindControl<TextBox>("ServerAddressTextBox");
        var tokenTextBox = this.FindControl<TextBox>("TokenTextBox");
        var instrumentComboBox = this.FindControl<ComboBox>("InstrumentComboBox");
        var portComboBox = this.FindControl<ComboBox>("PortComboBox");
        var baudRateComboBox = this.FindControl<ComboBox>("BaudRateComboBox");

        // 验证输入
        if (serverAddressTextBox == null || string.IsNullOrEmpty(serverAddressTextBox.Text))
        {
            NotificationHelper.ShowError("输入错误", "请输入服务器地址");
            return;
        }
        
        // 保存当前值到GV
        if (instrumentComboBox?.SelectedItem is IntegratedMeasuring.ViewModels.Entity.GC.InstrumentModelType instrumentModel)
        {
            GV.InstrumentModel = instrumentModel;
        }
        GV.SerialPortNum = portComboBox?.SelectedItem?.ToString() ?? "";
        GV.BaudRate = int.Parse(baudRateComboBox?.SelectedItem?.ToString() ?? "9600");
        GV.ServerAddress = serverAddressTextBox.Text;
        GV.Token = tokenTextBox?.Text ?? "";

        if (InstrumentControlHelper.Connect(GV.SerialPortNum, GV.BaudRate, out string msg))
        {
            // 保存到本地文件
            GV.SaveGVToLocalFile();

            // 显示成功通知
            NotificationHelper.ShowSuccess("登录成功", "已成功连接到仪器");

            // 触发登录事件
            LoginRequested?.Invoke(this, new LoginEventArgs
            {
                Instrument = instrumentComboBox?.SelectedItem?.ToString() ?? "",
                Port = portComboBox?.SelectedItem?.ToString() ?? "",
                BaudRate = baudRateComboBox?.SelectedItem?.ToString() ?? "",
                ServerAddress = serverAddressTextBox.Text,
                Token = tokenTextBox?.Text ?? ""
            });
            
            // 后台线程同步数据
            Task.Run(() =>
            {
                MesHandler.UploadOrderToMes();
                MesHandler.MergeAndRemoveDuplicatesAsync();
            });
        } else
        {
            // 显示错误信息
            NotificationHelper.ShowError("连接失败", $"无法连接到仪器：{msg}");
        }
    }
}

public class LoginEventArgs : EventArgs
{
    public string Instrument { get; set; } = "";
    public string Port { get; set; } = "";
    public string BaudRate { get; set; } = "";
    public string ServerAddress { get; set; } = "";
    public string Token { get; set; } = "";
}